package cn.ycl.auth.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.*;

/**
 * @Author YuanChangLiang
 * @Date 2020/11/10 20:47
 */
public class TokenUtil {
    /**
     * token过期时间
     */
    private static final long EXPIRE_TIME = 30 * 60 * 1000;
    /**
     * token秘钥
     */
    private static final String TOKEN_SECRET = "YuanChangLiang";


    /**
     * 生成签名，30分钟过期
     *
     * @param username  用户名
     * @param loginTime 登录时间
     * @return 生成的token
     */
    public static String sign(String username, Date loginTime) {
        try {
            // 设置过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");
            // 返回token字符串
            return JWT.create()
                    .withHeader(header)
                    .withClaim("loginName", username)
                    .withClaim("loginTime", loginTime)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 检验token是否正确
     *
     * @param token 需要校验的token
     * @return 校验是否成功
     */
    public static boolean verify(String token) {
        try {
            //设置签名的加密算法：HMAC256
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            String loginName = jwt.getClaim("loginName").asString();
            Date loginTime = jwt.getClaim("loginTime").asDate();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static Map<String, Object> getLoginInfo(String token) {
        Date now = new Date();
        HashMap<String, Object> hashMap = new HashMap<>();
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        String loginName = jwt.getClaim("loginName").asString();
        Date loginTime = jwt.getClaim("loginTime").asDate();
        if (!Objects.isNull(loginName)) {
            hashMap.put("loginName", loginName);
        }
        if (!Objects.isNull(loginTime)) {
            long between = (loginTime.getTime() - now.getTime()) / (1000 * 60);
            if (between > 30) {
                hashMap.put("loginTime", false);
            } else {
                hashMap.put("loginTime", true);
            }
        }
        return hashMap;
    }

    public static void main(String[] args) {
        verify("eyJhbGciOiJIUzI1NiIsIlR5cGUiOiJKd3QiLCJ0eXAiOiJKV1QifQ.eyJsb2dpblRpbWUiOjE2MzM3NDQxMTcsImxvZ2luTmFtZSI6ImFkbWluIiwiZXhwIjoxNjMzNzQ1OTE3fQ.iEeOOUL3m3xqfZIIBgCv97o3hZiqmM6E8F6xEch8KMc");
    }


    public static String createToken() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        return str.replace("-", "");
    }


}
